package com.alan.mongodb.elasticsearch;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;


/**
 * 使用时注入如下实例 private TransportClient     client;
 */
@Slf4j
//@Configuration
public class InitTransportConnection implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {

    private TransportClient client;

    @Value("${spring.elasticsearch.clusterName}")
    private String clusterName;

    @Value("${spring.elasticsearch.clusterServers}")
    private String[] clusterServers;

    @Override
    public void destroy() throws Exception {
        if (client != null) {
            client.close();
        }
    }

    @Override
    public TransportClient getObject() throws Exception {
        return client;
    }

    @Override
    public Class<?> getObjectType() {
        return TransportClient.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("------- transport init -------");
        Settings settings = Settings.builder()
                .put("cluster.name", this.clusterName)
                .put("transport.type", "netty3")
                .put("http.type", "netty3")
                .put("client.transport.sniff", true)
                .build();

        client = new PreBuiltTransportClient(settings);
        for (String node : clusterServers) {
            if (node.length() > 0) {
                String[] hostPort = node.split(":");
                client.addTransportAddress(new TransportAddress(InetAddress.getByName(hostPort[0]), Integer.parseInt(hostPort[1])));
            }
        }
        log.info("------- transport end -------");
    }
}
